package cn.xshi.iot.common.mqtt;

import cn.xshi.common.util.logger.Logback4jUtil;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.concurrent.ScheduledExecutorService;
/**
 * @Desc
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Configuration
public class MQTTSubsribeCallback extends Logback4jUtil implements MqttCallback {

    @Resource
    private MQTTSubsribe mqttSubsribe;

    private ScheduledExecutorService scheduled;// 定时任务——定时缓存查询的数据

    /**
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        super.info("MQTTSubsribeCallback","连接断开，可以做重连");
        this.mqttSubsribe.startReconnect();
    }

    /**
     *
     * @param topic
     * @param message
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        super.info("MQTTSubsribeCallback","接收消息主题 : " + topic);
        super.info("MQTTSubsribeCallback","接收消息Qos : " + message.getQos());
        super.info("MQTTSubsribeCallback","接收消息内容 : " + new String(message.getPayload()));
//        switch (topic){
//            case "CHAT":
//                //聊天工厂
//                new ChatFactory(topic,new String(message.getPayload())).start();
//                break;
//            default :
//                 super.info("MQTTSubsribeCallback","当前topic不存在业务处理 : " + topic);
//        }

//        this.scheduled = Executors.newSingleThreadScheduledExecutor();
//        //周期定时方法，可以在里面进行定时数据存储操作
//        this.scheduled.scheduleAtFixedRate(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//            //此处 120为每120秒执行一次
//        },0,120, TimeUnit.SECONDS);
    }

    /**
     *
     * @param token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
//        log.info("deliveryComplete---------" + token.isComplete());
    }
}
